﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using yq.IBase.Table;

namespace yq.IBase.Table
{
    public class TableHelper
    {
        static PdmReader mTest = null;

        /// <summary>
        /// 配置文件路径
        /// </summary>
        private const string _DefaultFilePath = "db.pdm";

        /// <summary>
        /// 站点配置文件路径
        /// </summary>
        private static string _ConfigFilePath = string.Empty;
        /// <summary>
        /// 站点配置文件路径
        /// </summary>
        private static string ConfigFilePath
        {
            get
            {
                if (string.IsNullOrEmpty(_ConfigFilePath))
                {
                    _ConfigFilePath = cn.Util.WebConfig.ConfigFilePath + _DefaultFilePath;
                }

                return _ConfigFilePath;
            }
        }


        static TableHelper()
        {
            PdmReader _mTest = new PdmReader(ConfigFilePath);
            _mTest.InitData();
            mTest = _mTest;
        }

        /// <summary>
        /// 表list
        /// </summary>
        /// <returns></returns>
        public static IList<TableInfo> GetTableList()
        { 
            return mTest.Tables;
        }

        /// <summary>
        /// 获取表
        /// </summary>
        /// <returns></returns>
        public static TableInfo GetTable<T>() where T : class ,new()
        {
            string className = new T().GetType().Name;

            return GetTable(className);
        }

        /// <summary>
        /// 获取表
        /// </summary>
        /// <param name="className"></param>
        /// <returns></returns>
        public static TableInfo GetTable(string className)
        {
            foreach (var info in mTest.Tables)
            {
                if (info.ClassName == className)
                {
                    return info;
                }
            }
            return null;
        }


        /// <summary>
        /// 获取列
        /// </summary>
        /// <param name="className"></param>
        /// <returns></returns>
        public static IList<ColumnInfo> GetColumns(string className)
        {
            foreach (var info in mTest.Tables)
            {
                if (info.ClassName == className)
                {
                    return info.Columns;
                }
            }
            return GetColumns(className);
        }

        /// <summary>
        /// 获取列
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IList<ColumnInfo> GetColumns<T>() where T : class ,new()
        {
            string className = new T().GetType().Name;

            return GetColumns(className);
        }

    }
}
